﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using KBEngine;
using UnityEngine.SceneManagement;

public class LoginPanel : MonoBehaviour
{
    public InputField AccountNameInput;
    public InputField PassWordInput;

	// Use this for initialization
	void Start ()
    {
        installEvents();
	}

    void installEvents()
    {
        KBEngine.Event.registerOut("onLoginFailed", this, "onLoginFailed");
        KBEngine.Event.registerOut("onLoginSuccessfully", this, "onLoginSuccessfully");
    }

    public void onLoginFailed(UInt16 failedcode)
    {
        print("登录失败！" + "  " + failedcode.ToString() + "  " + KBEngineApp.app.serverErr(failedcode));
    }

    public void onLoginSuccessfully(UInt64 rndUUID, Account accountEntity)
    {
        GameManager.GetInstance().showWaiting("登录成功！", 1);
        print("isNewPlayer" + accountEntity.IsNewChar);
        print("playerId_base" + accountEntity.CharId_base);
        print("playerName_base" + accountEntity.CharName_base);

        //进入大厅
        SceneManager.LoadScene("hall");
    }

    // 当 MonoBehaviour 将被销毁时调用此函数
    private void OnDestroy()
    {
        KBEngine.Event.deregisterOut(this);
    }

    public void ClickLogin()
    {
        Login();
    }

    private void Login()
    {
        if (AccountNameInput.text == "" || PassWordInput.text == "")
        {
            GameManager.GetInstance().showMessagePanel("账号或密码不能为空！", () =>
            {
                AccountNameInput.text = "";
                PassWordInput.text = "";
            });
            return;
        }

        //发起登录消息
        GameManager.GetInstance().showWaiting("正在连接中...", 10, () =>
        {
            GameManager.GetInstance().showMessagePanel("连接超时");
        });
        KBEngine.Event.fireIn("login", AccountNameInput.text, PassWordInput.text, System.Text.Encoding.UTF8.GetBytes(Application.platform.ToString()));
    }
}
